//
//  VRLoginViewController.m
//  VRFirefighting
//
//  Created by Veer on 2018/8/10.
//  Copyright © 2018年 Veer. All rights reserved.
//

#import "VRLoginViewController.h"

#import "VRRegisterViewController.h"
#import "VRModifyPwdViewController.h"

#import "NSString+Tools.h"

@interface VRLoginViewController () <UITextFieldDelegate>

@property (nonatomic, strong) UIButton *loginBtn;

@property (nonatomic, strong) NSMutableArray<UIView *> *inputViewArray;

@property (nonatomic, strong) NSMutableArray<UIView *> *realShowInputViewArray;

@end

@implementation VRLoginViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.inputViewArray = [NSMutableArray array];
    self.realShowInputViewArray = [NSMutableArray array];
    self.fd_prefersNavigationBarHidden = YES;
    
    [self setupSubView];
}

- (void)setupSubView
{
    UIImageView *bgImgView = [[UIImageView alloc] init];
    bgImgView.tag = 1000;
    bgImgView.image = [UIImage imageNamed:@"login_bg"];
    bgImgView.frame = CGRectMake(0, 0, kScreenWidth, kScreenHeight);
    [self.view addSubview:bgImgView];
    
    UILabel *titleLbl = [[UILabel alloc] init];
    titleLbl.text = @"智慧消防云";
    titleLbl.textColor = RGB(255, 255, 255);
    titleLbl.font = VRFont(22);
    [self.view addSubview:titleLbl];
    [titleLbl mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(80);
        make.top.mas_equalTo(100);
    }];
    
    
    UIView *contentView = [[UIView alloc] init];
    [self.view addSubview:contentView];
    [contentView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(0);
        make.top.mas_equalTo(titleLbl.mas_bottom).offset(40);
        make.width.mas_equalTo(kScreenWidth);
//        make.height.mas_equalTo(200);
    }];
    
    
    NSArray *imgNameArray = @[@"login_phone", @"login_pwd"];
    NSArray *placeholderArray = @[@"请输入手机号", @"请输入密码"];
    NSArray *titleArray = @[@"手机号", @"密码"];
    for (int i = 0; i < 2; i++) {
        
        UIView *inputView = [[UIView alloc] init];
        inputView.layer.borderColor = [UIColor whiteColor].CGColor;
        inputView.layer.borderWidth = 1.0;
        inputView.size = CGSizeMake(kScreenWidth - 40, 44);
        [contentView addSubview:inputView];
        
        UIImageView *iconImgView = [[UIImageView alloc] init];
        iconImgView.contentMode = UIViewContentModeScaleAspectFit;
        iconImgView.tag = 1000;
        iconImgView.image = [UIImage imageNamed:imgNameArray[i]];
        iconImgView.frame = CGRectMake(10, 0, 16, 16);
        iconImgView.centerY = 22;
        [inputView addSubview:iconImgView];
        
        UILabel *titleLbl = [[UILabel alloc] init];
        titleLbl.text = titleArray[i];
        titleLbl.textColor = RGB(255, 255, 255);
        titleLbl.font = VRFont(14);
        titleLbl.frame = CGRectMake(CGRectGetMaxX(iconImgView.frame) + 8, 0, 44, 44);
        [inputView addSubview:titleLbl];
        
        UITextField *tf = [[UITextField alloc] init];
        tf.tag = 1001;
        tf.font = VRFont(16);
        tf.textColor = [UIColor whiteColor];
        [tf setValue:RGB(107, 198, 255) forKeyPath:@"_placeholderLabel.textColor"];
        tf.placeholder = placeholderArray[i];
        tf.frame = CGRectMake(CGRectGetMaxX(titleLbl.frame) + 10, 0, kScreenWidth - CGRectGetMaxX(titleLbl.frame) - 10 - 80, 44);
        tf.delegate = self;
        [tf addTarget:self action:@selector(textFieldTextChanged:) forControlEvents:UIControlEventEditingChanged];
        [inputView addSubview:tf];
        
        tf.keyboardType = UIKeyboardTypeNumberPad;
        if (i == 0) {
            
            tf.text = [VRUser shareUser].mobile;
            tf.clearButtonMode = UITextFieldViewModeWhileEditing;
            tf.width = kScreenWidth - 132 - 30;
        }else if (i == 1) {
            
            tf.secureTextEntry = YES;
            tf.keyboardType = UIKeyboardTypeASCIICapable;
            
            // 按钮
            UIButton *viewPasswordBtn = [UIButton buttonWithType:UIButtonTypeCustom];
            [viewPasswordBtn setImage:[UIImage imageNamed:@"icon_password_visible"] forState:UIControlStateNormal];
            [viewPasswordBtn setImage:[UIImage imageNamed:@"icon_password_unvisible"] forState:UIControlStateSelected];
            [viewPasswordBtn addTarget:self action:@selector(onShowPasswordBtnClick:) forControlEvents:UIControlEventTouchUpInside];
            [inputView addSubview:viewPasswordBtn];
            viewPasswordBtn.frame = CGRectMake(kScreenWidth - 40 - 20 - 30, 0, 30, 20);
            viewPasswordBtn.centerY = 22;
        }
        
        CGFloat inputViewY = i * 44 + i * 20;
        inputView.frame = CGRectMake(20, inputViewY, kScreenWidth - 40, 44);
        [self.inputViewArray addObject:inputView];
    }
    
    
    [contentView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.bottom.mas_equalTo([self.inputViewArray lastObject]);
    }];
    
    // 按钮
    UIButton *loginBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    loginBtn.backgroundColor = RGB(78, 173, 57);
    loginBtn.layer.cornerRadius = 4;
    [loginBtn setTitle:@"立即登录" forState:UIControlStateNormal];
    loginBtn.titleLabel.font = VRFont(16);
    [loginBtn setTitleColor:RGB(255, 255, 255) forState:UIControlStateNormal];
    [loginBtn setTitleColor:RGB(120, 120, 120) forState:UIControlStateHighlighted];
    [loginBtn addTarget:self action:@selector(onLoginBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:loginBtn];
    self.loginBtn = loginBtn;
    [loginBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(self.view);
        make.top.mas_equalTo(contentView.mas_bottom).offset(50);
        make.width.mas_equalTo(kScreenWidth - 24);
        make.height.mas_equalTo(46);
    }];
    
    // 按钮
    UIButton *leftBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    leftBtn.layer.cornerRadius = 4;
    [leftBtn setTitle:@"立即注册" forState:UIControlStateNormal];
    leftBtn.titleLabel.font = VRFont(16);
    [leftBtn setTitleColor:RGB(255, 255, 255) forState:UIControlStateNormal];
    [leftBtn setTitleColor:RGB(200, 200, 200) forState:UIControlStateHighlighted];
    [leftBtn addTarget:self action:@selector(onRegisterBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:leftBtn];
    [leftBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(loginBtn);
        make.top.mas_equalTo(self.loginBtn.mas_bottom).offset(20);
        make.width.mas_equalTo(70);
        make.height.mas_equalTo(28);
    }];
    
    // 按钮
    UIButton *rightBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    rightBtn.layer.cornerRadius = 4;
    [rightBtn setTitle:@"忘记密码?" forState:UIControlStateNormal];
    rightBtn.titleLabel.font = VRFont(16);
    [rightBtn setTitleColor:RGB(255, 255, 255) forState:UIControlStateNormal];
    [rightBtn setTitleColor:RGB(200, 200, 200) forState:UIControlStateHighlighted];
    rightBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
    [rightBtn addTarget:self action:@selector(onForgetBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:rightBtn];
    [rightBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(loginBtn);
        make.top.mas_equalTo(leftBtn);
        make.width.mas_equalTo(80);
        make.height.mas_equalTo(28);
    }];
}


#pragma mark - networking
- (void)login
{
    
    UITextField *mobileTf = [self.inputViewArray[0] viewWithTag:1001];
    UITextField *passwordTf = [self.inputViewArray[1] viewWithTag:1001];
    
    NSTimeInterval timeStamp = [[NSDate date] timeIntervalSince1970];
    
    NSString *timeStampStr = [NSString stringWithFormat:@"%.0lf", timeStamp];
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[@"phone"] = mobileTf.text;
    param[@"pwd"] = passwordTf.text;
    param[@"timestamp"] = timeStampStr;
    
    
    NSString *signStr = [NSString stringWithFormat:@"phone=%@&pwd=%@&timestamp=%@&key=%@", mobileTf.text, passwordTf.text, timeStampStr, @"O0bfiXjlyjbNq1jP5cG2DyfZDTBma1Dd"];
    
    NSString *sign = signStr.md5;
//
//    param[@"sign"] = signStr.md5;
    
    weakify(self)
    [JKNetworking postWithSign:login_url parameters:param success:^(NSDictionary *responseObject) {
        
        strongify(self)
        NSLog(@"responseObject:%@", responseObject);
        NSInteger code = [responseObject[@"state"] integerValue];
        NSString *msg = responseObject[@"msg"];
        
        if (code == 0) {
            
            dispatch_async(dispatch_get_main_queue(), ^{

                [VRUser shareUser].token = responseObject[@"data"][@"fID"];
                [VRUser shareUser].CustomerName = responseObject[@"data"][@"CustomerName"];
                [VRUser shareUser].fIsAreaManage = [responseObject[@"data"][@"fIsAreaManage"] integerValue];
                [VRUser shareUser].isLogined = YES;
                [VRUser shareUser].mobile = mobileTf.text;
                [[NSNotificationCenter defaultCenter] postNotificationName:kLoginSuccess object:nil];
            });
        }else if(msg.length > 0){
            [SVProgressHUD showErrorWithStatus:msg];
        }
    } error:^(NSError * _Nonnull error) {
        [SVProgressHUD showErrorWithStatus:@"未知错误"];
    }];
}


#pragma mark - action
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [self.view endEditing:YES];
}

- (void)onShowPasswordBtnClick:(UIButton *)sender
{
    sender.selected = !sender.selected;
    
    UITextField *tf = [sender.superview viewWithTag:1001];
    
    tf.enabled = NO;
    tf.secureTextEntry = !sender.selected;
    
    tf.enabled = YES;
    [tf becomeFirstResponder];
}


#pragma mark - aciton
- (void)onLoginBtnClick:(UIButton *)sender
{
    
    [self.view endEditing:YES];
    
    UITextField *mobileTf = [self.inputViewArray[0] viewWithTag:1001];
    UITextField *passwordTf = [self.inputViewArray[1] viewWithTag:1001];
    if (mobileTf.text.length == 0) {
        [SVProgressHUD showErrorWithStatus:@"手机号不能为空"];
        return;
    }
    
    if ([NSString valiMobile:mobileTf.text]) {
        [SVProgressHUD showErrorWithStatus:@"请输入正确的手机号"];
        return;
    }
    
    if (passwordTf.text.length == 0) {
        [SVProgressHUD showErrorWithStatus:@"密码不能为空"];
        return;
    }

    [self login];
}

- (void)onRegisterBtnClick:(UIButton *)sender
{
    VRRegisterViewController *loginVc = [[VRRegisterViewController alloc] init];
    [self.navigationController pushViewController:loginVc animated:YES];

    UITextField *mobileTf = [self.inputViewArray[0] viewWithTag:1001];
    weakify(self)
    loginVc.returnBlock = ^(NSString *phoneNumber) {

        strongify(self)
        dispatch_async(dispatch_get_main_queue(), ^{
            
            mobileTf.text = phoneNumber;
        });
    };
}


- (void)onForgetBtnClick:(UIButton *)sender
{
    VRModifyPwdViewController *loginVc = [[VRModifyPwdViewController alloc] init];
    [self.navigationController pushViewController:loginVc animated:YES];
}


#pragma mark - delegate
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    
    UITextField *tf = [self.inputViewArray[0] viewWithTag:1001];
    if ([string length] > 0) {
        if (textField == tf) {
            
            if (![self deptNumInputShouldNumber:string]) {
                return NO;
            }
            if (textField.text.length >= 11) {
                return NO;
            }
        } else {
            
            //            if (![self deptNumInputShouldNumber:string]) {
            //                return NO;
            //            }
            //            if (textField.text.length >= 6) {
            //                return NO;
            //            }
        }
    }
    return YES;
}


- (void)textFieldTextChanged:(UITextField *)textField
{
    
    UITextField *tf = [self.inputViewArray[0] viewWithTag:1001];
//    if (textField == tf) {
//
//        self.getVerCodeBtn.enabled = NO;
//
//        if (self.isCountDown) {
//            [self stopCountDown];
//            [self.getVerCodeBtn setTitle:@"获取验证码" forState:(UIControlStateNormal)];
//            [self.getVerCodeBtn setTitle:@"获取验证码" forState:(UIControlStateDisabled)];
//        }
//
//        if (textField.text.length == 11) {
//
//            BOOL validate = [textField.text hasPrefix:@"1"];
//            self.getVerCodeBtn.enabled = validate;
//        }
//    }else{
//
//        //        if (textField.text.length == 6 && self.usernameTF.text.length == 11) {
//        //
//        //            self.loginBtn.enabled = YES;
//        //        }else{
//        //            self.loginBtn.enabled = NO;
//        //        }
//    }
}


- (BOOL)deptNumInputShouldNumber:(NSString *)str
{
    NSString *regex = @"[0-9]*";
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",regex];
    if ([pred evaluateWithObject:str]) {
        return YES;
    }
    return NO;
}

@end
